<template>
  <div class="graph-visualization" v-loading="loading" element-loading-text="加载中...">
    <el-carousel :interval="4000" type="card" height="100px" :autoplay="false" :loop="false" arrow='never'>
      <el-carousel-item @click="changeCategory('生活')">
        <h3 text="2xl" justify="center">生活</h3>
      </el-carousel-item>
      <el-carousel-item @click="changeCategory('科技')">
        <h3 text="2xl" justify="center">科技</h3>
      </el-carousel-item>
      <el-carousel-item @click="changeCategory('人文')">
        <h3 text="2xl" justify="center">人文</h3>
      </el-carousel-item>
      <el-carousel-item @click="changeCategory('军事')">
        <h3 text="2xl" justify="center">军事</h3>
      </el-carousel-item>
    </el-carousel>
    <KnowledgeGraph 
      :nodes="nodes" 
      :links="links" 
      :stats="stats"
      v-if="nodes.length > 0 && links.length > 0"
    />
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElLoading } from 'element-plus'
import KnowledgeGraph from '@/components/KnowledgeGraph.vue'

const loading = ref(false)
const nodes = ref([])
const links = ref([])
const stats = ref({
  nodeCount: 0,
  edgeCount: 0
})
const category = ref('生活')
const changeCategory = async(categoryPrompt) => {
  category.value = categoryPrompt
  await loadGraphData()
}
const loadGraphData = async () => {
  loading.value = true
  nodes.value = []
  links.value = []
  
  try {
    const response = await fetch(`http://localhost:8000/api/graph/visualization/${category.value}`)
    const data = await response.json()
    
    console.log('Raw API response:', data)
    
    if (data.code === 200) {
      const graphData = data.data || {}
      console.log('Graph data:', graphData)
      
      // First update stats
      stats.value = {
        nodeCount: graphData.nodeCount || 0,
        edgeCount: graphData.edgeCount || 0
      }
      
      // Then update nodes and links
      nodes.value = Array.isArray(graphData.nodes) ? graphData.nodes : []
      links.value = Array.isArray(graphData.links) ? graphData.links : []
      
      console.log('Updated state:', {
        nodes: nodes.value.length,
        links: links.value.length,
        stats: stats.value
      })
    } else {
      console.error('API error:', data.message || '未知错误')
    }
  } catch (error) {
    console.error('Error loading graph data:', error)
  } finally {
    loading.value = false
  }
}

onMounted(() => {
  loadGraphData()
})
</script>

<style scoped>
.graph-visualization {
  width: 100vw;
  height: 100vh;
  padding: 20px;
  padding-top: 100px;
  display: flex;
  flex-direction: column;
  background: white;
  margin: 0;
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
}
.el-carousel__item h3 {
  color: #475669;
  opacity: 0.75;
  line-height: 100px;
  margin: 0;
  text-align: center;
}

.el-carousel__item:nth-child(2n) {
  background-color: #99a9bf;
}

.el-carousel__item:nth-child(2n + 1) {
  background-color: #d3dce6;
}
</style> 